import requests
import os
import sys
sys.path.append('../backend')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HuaXianGuan.settings')

import django
django.setup()

from apps.flowers.models import Flower, FlowerImage
from common.utils.oss_utils import FileOss

def update_flower_image_table():
    """更新flower_image表中的粉郁金香花束图片"""
    
    # 找到粉郁金香花束
    flower = Flower.objects.filter(name='粉郁金香花束').first()
    if not flower:
        print("未找到粉郁金香花束")
        return
    
    print(f"找到花朵: {flower.name}")
    
    # 查找该花朵的图片记录
    flower_images = FlowerImage.objects.filter(flower=flower)
    print(f"找到 {flower_images.count()} 张图片记录")
    
    if not flower_images.exists():
        print("没有找到图片记录，创建新的图片记录")
        # 如果没有图片记录，创建一个新的
        flower_image = FlowerImage.objects.create(
            flower=flower,
            image_url="",  # 先创建空的，稍后更新
            is_primary=True
        )
        flower_images = [flower_image]
    
    # 下载正确的郁金香图片
    tulip_urls = [
        "https://images.pexels.com/photos/36729/tulip-flower-bloom-pink.jpg?auto=compress&cs=tinysrgb&w=800",
        "https://images.pexels.com/photos/1379636/pexels-photo-1379636.jpeg?auto=compress&cs=tinysrgb&w=800",
        "https://images.pexels.com/photos/1379637/pexels-photo-1379637.jpeg?auto=compress&cs=tinysrgb&w=800"
    ]
    
    oss_client = FileOss()
    
    for i, url in enumerate(tulip_urls):
        try:
            print(f"尝试下载图片 {i+1}: {url}")
            
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            }
            
            response = requests.get(url, headers=headers, timeout=15)
            if response.status_code == 200:
                print(f"成功下载，大小: {len(response.content)} bytes")
                
                # 上传到OSS
                oss_path = f"flowers/粉郁金香花束_{i+1}.jpg"
                oss_url = oss_client.get_oss_image_url(oss_path, response.content)
                
                if oss_url:
                    # 更新第一张图片记录
                    flower_image = flower_images[0]
                    flower_image.image_url = oss_url
                    flower_image.save()
                    
                    print(f"✓ 成功更新flower_image表中的粉郁金香花束图片: {oss_url}")
                    
                    # 验证更新
                    updated_image = FlowerImage.objects.get(id=flower_image.id)
                    print(f"验证: 图片ID {updated_image.id} 的URL已更新为: {updated_image.image_url}")
                    return True
                else:
                    print("✗ OSS上传失败")
            else:
                print(f"✗ HTTP错误: {response.status_code}")
                
        except Exception as e:
            print(f"✗ 下载失败: {e}")
            continue
    
    print("✗ 所有图片都下载失败")
    return False

if __name__ == "__main__":
    update_flower_image_table()